/* 
 -----------------------------------------------------------------------------
                   Cogaen - Component-based Game Engine (v3)
 -----------------------------------------------------------------------------
 This software is developed by the Cogaen Development Team. Please have a 
 look at our project home page for further details: http://www.cogaen.org
    
 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 Copyright (c) Roman Divotkey, 2010-2011

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
*/

package org.cogaen.core;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.cogaen.entity.EntityManager;
import org.cogaen.event.EventManager;
import org.cogaen.logging.LoggingService;
import org.cogaen.name.NameService;
import org.cogaen.state.GameStateManager;
import org.cogaen.task.TaskManager;
import org.cogaen.time.Clock;
import org.cogaen.time.TimeService;

/**
 * Manages and updates services. 
 * 
 * <p>In general there exists only one core within a game. 
 * The core is used to access all available services. Whenever the core is
 * accessible, all installed services are accessible. The core can be seen 
 * as a <strong>service locator</strong>. 
 * 
 * <p>
 * New services can be installed and attached to a certain instance of
 * core. Because some services need to be continuously updated, the core's 
 * {@code update} method must be called within the game loop and provided with 
 * the elapsed time since the last update.
 * </p>
 * 
 * The core keeps track of the game time, however it is recommended to use
 * the {@code TimeService} to access the current game time or delta time.
 * 
 * <hr>
 * <p>
 * The package {@code org.cogaen.time} provides the class {@code Clock} that
 * can be used to measure the elapsed time. Here is an example of an typical
 * game loop that updates the core every iteration.
 * </p>
 * 
 * <pre>
 * Clock clock = new Clock();
 * 
 * while (true) {
 *    clock.tick();
 *    core.update( clock.getDelta() );
 *    
 *    //render scene and entities
 * }
 * </pre>
 * 
 * @see Service
 * @see UpdateableService
 * @see Clock
 */
public class Core {
	
	private static final String LOGGING_SOURCE = "Core";
	private Map<String, Service> services = new HashMap<String, Service>();	
	private List<UpdateableService> updateables = new ArrayList<UpdateableService>();
	private double deltaTime = 0.0;
	private double time = 0.0;
	
	/**
	 * Creates a new instance and installs a set of commonly used services.
	 * <p>
	 * Following services will be installed:
	 * <ul>
	 *  <li>{@link LoggingService}</li>
	 *  <li>{@link NameService}</li>
	 *  <li>{@link TimeService}</li>
	 *  <li>{@link TimeService}</li>
	 *  <li>{@link TimeService}</li>
	 *  <li>{@link TaskManager}</li>
	 *  <li>{@link EventManager}</li>
	 *  <li>{@link EntityManager}</li>
	 *  <li>{@link GameStateManager}</li>
	 * </ul>
	 * </p>
	 * 
	 * <p><strong>Note:</strong> LoggingServices will be configured to use
	 * logging level {@code LoggingService.WARNING}.</p>
	 * 
	 * @return new instance of {@code Core} with standard services installed.
	 */
	public static Core createCoreWithStandardServices() {
		return createCoreWithStandardServices(LoggingService.WARNING);
	}

	/**
	 * Creates a new instance and installs a set of commonly used services.
	 * <p>
	 * Following services will be installed:
	 * <ul>
	 *  <li>{@link LoggingService}</li>
	 *  <li>{@link NameService}</li>
	 *  <li>{@link TimeService}</li>
	 *  <li>{@link TimeService}</li>
	 *  <li>{@link TimeService}</li>
	 *  <li>{@link TaskManager}</li>
	 *  <li>{@link EventManager}</li>
	 *  <li>{@link EntityManager}</li>
	 *  <li>{@link GameStateManager}</li>
	 * </ul>
	 * </p>
	 * 
	 * @param loggingLevel initial logging level used to configure logging service.
	 * 
	 * @return new instance of {@code Core} with standard services installed.
	 */
	public static Core createCoreWithStandardServices(int loggingLevel) {
		Core core = new Core();
		core.installService( new LoggingService(loggingLevel) );
		core.installService( new NameService() );
		core.installService( new TimeService() );
		core.installService( new TaskManager() );
		core.installService( new EventManager() );
		core.installService( new EntityManager() );
		core.installService( new GameStateManager() );
		
		return core;
	}
	
	/**
	 * Installs specified service. 
	 * If specified service is an instance of {@code UpdateableService},
	 * it will be updated once every iteration of the game loop.
	 * 
	 * @param service {@code Service} to be installed.
	 * @throws RuntimeException if name of specified service is not unique.
	 * @see Service
	 */
	public void installService(Service service) {
		if (hasService(service.getName())) {
			throw new RuntimeException("service '" + service.getName()+ "' already installed");
		}
		
		this.services.put(service.getName(), service);
		if (service instanceof UpdateableService) {
			this.updateables.add((UpdateableService) service);
		}
		service.initialize(this);
		
		if (hasService(LoggingService.NAME)) {
			String msg;
			
			if (service instanceof UpdateableService) {
				msg = "updateable service '" + service.getName() + "' installed";				
			} else {
				msg = "service '" + service.getName() + "' installed";				
			}			
			LoggingService.getInstance(this).logDebug(LOGGING_SOURCE, msg);
		}
	}
	
	/**
	 * Tests if service with specified name exists.
	 * 
	 * @param name {@code String} defining unique name of requested service.
	 * @return {@code true} if service exists, {@code false} otherwise.
	 */
	public boolean hasService(String name) {
		return this.services.containsKey(name);
	}

	/**
	 * Returns service with specified name.
	 * 
	 * @param name {@code String} defining unique name of the service to be returned.
	 * @return Service with specified name.
	 * @throws RuntimeException if no service with specified name exists.
	 */
	public Service getService(String name) {
		Service service = this.services.get(name);
		if (service == null) {
			throw new RuntimeException("service '" + name + "' not found");
		}
		
		return service;
	}
	
	/**
	 * Returns current delta time in seconds.
	 * 
	 * @return current delta time in seconds.
	 */
	public double getDeltaTime() {
		return this.deltaTime;
	}
	
	/**
	 * Returns the current absolute game time in seconds.
	 * <p>
	 * <strong>Note:</strong> Time managed by the core cannot be reseted or
	 * manipulated. Use TimeService and the provided {@code Timer} objects in 
	 * order to pause, resume or reset game time.
	 * </p>
	 * 
	 * @return absolute game time in seconds.
	 */
	public double getTime() {
		return this.time;
	}
	
	/**
	 * Updates game time and all updateable services.
	 * <p>
	 * This method is usually called within the game loop.
	 * <p>
	 * 
	 * @param dt elapsed time in seconds.
	 */
	public void update(double dt) {
		this.deltaTime = dt;
		this.time += dt;
		
		for (UpdateableService service : this.updateables) {
			service.update();
		}
	}

}
